package com.wisedu.mobile.auth.service.impl.v1.ids;

import com.wisedu.mobile.common.BaseException;
import com.wisedu.mobile.common.constant.UserConstants;
import com.wisedu.mobile.common.domain.LoginUser;
import com.wisedu.mobile.common.domain.SysMenu;
import com.wisedu.mobile.common.domain.SysRole;
import com.wisedu.mobile.common.domain.SysUser;
import com.wisedu.mobile.common.service.ISysUserService;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.autoconfigure.condition.ConditionalOnProperty;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.core.userdetails.UserDetailsService;
import org.springframework.security.core.userdetails.UsernameNotFoundException;
import org.springframework.stereotype.Service;

import java.util.HashSet;
import java.util.Set;

/**
 * 用户验证处理
 *
 * @author hj
 */
@Service
@ConditionalOnProperty(prefix = "auth", name = "way", havingValue = "ids")
public class UserDetailsServiceImpl implements UserDetailsService
{
    private static final Logger log = LoggerFactory.getLogger(UserDetailsServiceImpl.class);

    @Autowired
    private ISysUserService userService;


    @Override
    public UserDetails loadUserByUsername(String loginname) throws UsernameNotFoundException
    {
        SysUser user = userService.selectUserByLoginName(loginname);
        if (user == null) {
            //TODO get ids uid&uname  role  dept
            log.info("IDS。。。。登录用户：{} .", loginname);
            throw new UsernameNotFoundException("IDS。。。。登录用户：" + loginname + " 不存在");
            //TODO add user user_role dept
//            user = new SysUser();

        } else if (UserConstants.USER_BLOCKED.equals(user.getStatus())) {
            log.info("登录用户：{} 已被停用.", loginname);
            throw new BaseException("对不起，您的账号：" + loginname + " 已停用");
        }

        userService.selectRoleByUser(user);
        Set<String> perms = new HashSet<String>();
        // 管理员拥有所有权限
        if (user.isAdmin()) {
            perms.add("*:*:*");
        } else {
            for (SysRole role : user.getRoles()) {
                for (SysMenu menu : role.getMenus()) {
                    perms.add(menu.getUrl()+":"+menu.getHttpMethod());
                }
            }
        }
        return new LoginUser(user, perms);
    }
}
